<?php

namespace app\mobileapp\controller;


use think\Db;

class Member extends Base
{

    /**
     * User: Simony
     * Function:设置邀请码
     */
    public function setInviteCode()
    {
        $memberId = $this->memberId;

        //params
        $invite_code = input('post.invite_code', '');

        Db::startTrans();
        $res = model('common/member/MemberLogic', 'logic')->setInviteCode($memberId, $invite_code);
        $res['code'] == SUCCESS ? Db::commit() : Db::rollback();

        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function:头像上传
     */
    public function uploadAvatar()
    {
        $memberId = $this->memberId;
        $type = input('post.type', 1);

        //model or logic
        $fileLogic = model('common/file/FileLogic', 'logic');
        $memberModel = model('common/member/Member');

        $upload_res = $type == 1 ? $fileLogic->uploadImg(config('app.image_path.avatar'), false) : $fileLogic->base64Image(config('app.image_path.avatar'), false);
        if ($upload_res['code'] != SUCCESS) $this->api_ajaxReturn($upload_res['code'], $upload_res['msg']);

        $member = $memberModel->getInfoById($memberId);


        if ($member['avatar'] != '') model('common/file/FileLogic', 'logic')->deleteFile($member['avatar']);


        //更新头像
        $res = $memberModel->edit(['id' => $memberId], ['avatar' => $upload_res['result']['absoluteUrl']]);
        $res ? $this->api_ajaxReturn(SUCCESS, '上传头像成功', ['absoluteUrl' => $upload_res['result']['absoluteUrl']]) : $this->api_ajaxReturn(ERROR, '上传失败');

    }

    /**
     * User: Simony
     * Function:修改会员资料
     */
    public function updateMember()
    {
        $memberId = $this->memberId;

        //model
        $memberModel = model('common/member/Member');
        $member = $memberModel->getMemberInfo($memberId);

        if ($member['parent_id'] > 0) { //invite_code
//        if ($member['invite_code'] > 0) {
            $config_num = config('app.member.month_update_num'); //这里后面改成读取配置
            if (date('Y-m', time()) == date('Y-m', $member['update_time'])) { //同一个月
                $surplus_num = $config_num - $member['month_update_num'];
                $surplus_num = $surplus_num > 0 ? $surplus_num : 0;
                $month_update_num = $member['month_update_num'] + 1;
            } else {
                $surplus_num = $config_num;
                $month_update_num = 1;
            }
            if ($surplus_num == 0) $this->api_ajaxReturn(ERROR, '本月修改次数已用光');
        } else {
            $month_update_num = 0;
        }

        //params
        $data = [
            'nickname' => input('post.nickname/s'),
            'province' => input('post.province/d'),
            'city' => input('post.city/d'),
            'district' => input('post.district/d'),
            'birthday' => input('post.birthday/s'),
            'profession' => input('post.profession/s'),
            'content_types' => input('post.content_types/s'),
            'expect_object' => input('post.expect_object/s'),
            'wechat' => input('post.wechat/s'),
            'wechat_hide' => input('post.wechat_hide', 0),
            'update_time' => time(),
            'month_update_num' => $month_update_num
        ];
        $height = input('post.height/d');
        $weight = input('post.weight/d');
        $introduce = input('post.introduce');
        if (!empty($height)) $data['height'] = $height;
        if (!empty($weight)) $data['weight'] = $weight;
        if (!empty($introduce)) $data['introduce'] = $introduce;

        $valdate = validate('mobileapp/member');
        if (!$valdate->check($data, [], 'updateMember')) $this->api_ajaxReturn(ERROR, $valdate->getError());

        $res = $memberModel->editByID($memberId, $data);
        $res ? $this->api_ajaxReturn(SUCCESS, '修改成功') : $this->api_ajaxReturn(ERROR, '修改失败');
    }


    /**
     * User: Simony
     * Function:关注、取消、拉黑
     */
    public function follow()
    {
        $memberId = $this->memberId;
        $been_member_id = input('post.been_member_id/d');
        $type = input('post.type/d', 0);

        if (!in_array($type, [0, 1, 2])) $this->api_ajaxReturn(ERROR, '类型有误');

        $res = model('common/member/MemberLogic', 'logic')->follow($memberId, $been_member_id, $type);
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function:上传文件（相册+真人认证照片+真人视频照片）
     */
    public function uploadAlbum()
    {
        $memberId = $this->memberId;

        $type = input('post.type/d', 1);
        $red_packet_price = input('post.red_packet_price', 0.00);
        $upload_type = input('post.upload_type/d', 1);

        $add_data = [
            'member_id' => $memberId,
            'table_id' => $memberId,
            'type' => $type,
            'status' => 1,
            'create_time' => time()
        ];

        if (!in_array($type, [1, 2, 3, 4, 5, 6, 7])) $this->api_ajaxReturn(ERROR, '文件类型错误');
        if ($type == 3) {
            if ($red_packet_price <= 0) $this->api_ajaxReturn(ERROR, '金额错误');
            $add_data['red_packet_price'] = $red_packet_price;
        }


        //upload
        $fileLogic = model('common/file/FileLogic', 'logic');
        $upload_res = $upload_type == 1 ? $fileLogic->uploadImg(config('app.image_path.ablbum') . DS . $type) : $fileLogic->base64Image(config('app.image_path.ablbum') . DS . $type);
        if ($upload_res['code'] != SUCCESS) $this->api_ajaxReturn($upload_res['code'], $upload_res['msg']);
        $add_data['url'] = $upload_res['result']['absoluteUrl'];


        $res = model('common/member/File')->add($add_data);
        $res ? $this->api_ajaxReturn(SUCCESS, '上传成功', ['id' => $res]) : $this->api_ajaxReturn(ERROR, '上传失败');
    }

    /**
     * User: Simony
     * Function:上传真人认证照片
     */
    public function uploadRealNameImg()
    {
        $memberId = $this->memberId;
        $upload_type = input('post.upload_type/d', 1);
        $type = 7;


        $fileLogic = model('common/file/FileLogic', 'logic');
        $upload_res = $upload_type == 1 ? $fileLogic->uploadImg(config('app.image_path.ablbum') . DS . $type, false) : $fileLogic->base64Image(config('app.image_path.ablbum') . DS . $type, false);
        if ($upload_res['code'] != SUCCESS) $this->api_ajaxReturn($upload_res['code'], $upload_res['msg']);
        $absoluteUrl = $upload_res['result']['absoluteUrl'];

        Db::startTrans();
        $fileModel = model('common/member/File');
        $where = ['member_id' => $memberId, 'type' => $type];
        $file = $fileModel->getInfo($where);
        if ($file) {
            if ($file['url'] != '') $fileLogic->deleteFile($file['url']);
            $res = $fileModel->edit($where, ['url' => $absoluteUrl]);
            $res = $file['id'];
//            echo $fileModel->getLastSql();die;
        } else {
            $add_data = [
                'member_id' => $memberId,
                'table_id' => $memberId,
                'type' => $type,
                'status' => 1,
                'create_time' => time()
            ];
            $add_data['url'] = $absoluteUrl;
            $res = $fileModel->add($add_data);
        }
        if (!$res) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '上传失败');
        }
        Db::commit();
        $this->api_ajaxReturn(SUCCESS, '上传成功', ['id' => $res]);
    }


    /**
     * User: Simony
     * Function:删除相册图片
     */
    public function delBlbumImg()
    {
        $memberId = $this->memberId;
        $id = input('post.id/d');

        $fileModel = model('common/member/File');
        $file = $fileModel->getInfo(['member_id' => $memberId, 'id' => $id]);
        if (empty($file)) $this->api_ajaxReturn(ERROR, '数据不存在');

        $res = $fileModel->delByID($id);
        if (true) {
            $fileLogic = model('common/file/FileLogic', 'logic');
            $path_info = pathinfo($file['url']);
            if ($file['url'] != '') $fileLogic->deleteFile($file['url']); //先删除文件

            //注意
            if ($file['url'] != '' && in_array($file['type'], [2, 3])) $fileLogic->deleteFile($path_info['dirname'] . DS . md5($file['url']) . '.' . $path_info['extension']); //删除红包+阅后

            $this->api_ajaxReturn(SUCCESS, '删除成功');
        }
        $this->api_ajaxReturn(ERROR, '删除失败');
    }


    /**
     * User: Simony
     * Function: 设置会员相册权限
     */
    public function setAlbumAuth()
    {
        $memberId = $this->memberId;
        $album_auth = input('post.album_auth', 0);
        $album_price = input('post.album_price', 0);

        $res = model('common/member/MemberLogic', 'logic')->setAlbumAuth($memberId, $album_auth, $album_price);
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function:举报会员
     */
    public function reportMember()
    {
        $memberId = $this->memberId;
        $report_member_id = input('post.report_member_id/d');
        $type_id = input('post.type_id/d');
        $desc = input('post.desc/s');

        $data = [
            'report_member_id' => $report_member_id,
            'desc' => $desc,
            'type_id' => $type_id,
        ];

        $valdate = validate('mobileapp/reportUser');
        if (!$valdate->check($data, [], 'reportMember')) $this->api_ajaxReturn(ERROR, $valdate->getError());

        $res = model('common/member/MemberLogic', 'logic')->reportMember($memberId, $report_member_id, $type_id, $desc);
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User: Simony
     * Function:会员基本信息
     */
    public function getMemberBaseInfo()
    {
        $memberId = $this->memberId;
        $show_member_id = input('id/d');

        $res = model('common/member/MemberLogic', 'logic')->getMemberBaseInfo($memberId, $show_member_id);
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function: 评价类型列表
     */
    public function getEvaluateTypeList()
    {
        //param
        $id = input('post.id/d');
        //judge
        if (empty($id)) $this->api_ajaxReturn(ERROR, '参数不能为空');

        //get data
        $res = model('common/member/MemberLogic', 'logic')->getEvaluateTypeList($id);


        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User: Simony
     * Function:评价
     */
    public function evaluate()
    {
        $memberId = $this->memberId;


        $been_member_id = input('post.been_member_id/d', 0);
        $type_ids = input('post.type_ids', 0);

        if ($been_member_id <= 0) $this->api_ajaxReturn(ERROR, '参数错误');

        //model
        $evaluateLogLogic = model('common/evaluate/EvaluateLogLogic', 'logic');

        $res = $evaluateLogLogic->evaluate($memberId, $been_member_id, $type_ids);
        $res['code'] == SUCCESS ? Db::commit() : Db::rollback();
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function: personalCenter
     */
    public function personalCenter()
    {
        $memberId = $this->memberId;
        $res = model('common/member/MemberLogic', 'logic')->personalCenter($memberId);
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);

    }

    /**
     * User: Simony
     * Function:会员相册
     */
    public function memberAblum()
    {
        $memberId = $this->memberId;
        $show_member_id = input('post.show_member_id/d');

        if (empty($show_member_id)) $this->api_ajaxReturn(ERROR, '参数错误');

        Db::startTrans();
        $res = model('common/member/MemberLogic', 'logic')->memberAblum($memberId, $show_member_id);
        $res['code'] == SUCCESS ? Db::commit() : Db::rollback();

        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function:用户修改资料
     */
    public function getMember()
    {
        $memberId = $this->memberId;

        $field = "m.id,avatar,nickname,name as city_name,province,district,city,birthday,profession,content_types,expect_object,wechat,wechat_hide,height,weight,introduce,update_time,month_update_num,invite_code";
        $data = model('common/member/Member')->getMemberInfo($memberId, $field);
        unset($data['long_lat_geometry']);

        $config_num = config('app.member.month_update_num'); //这里后面改成读取配置
        if (date('Y-m', time()) == date('Y-m', $data['update_time'])) { //同一个月
            $surplus_num = $config_num - $data['month_update_num'];
            $data['surplus_num'] = $surplus_num > 0 ? $surplus_num : 0;
        } else {
            $data['surplus_num'] = $config_num;
        }

        unset($data['update_time']);
        unset($data['month_update_num']);

        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }


    /**
     * User: Simony
     * Function:查看社交账号
     */
    public function viewSocialAccount()
    {
        $memberId = $this->memberId;
        $been_member_id = input('post.show_member_id/d', 0);

        Db::startTrans(); //里面有更新付费记录操作的可能
        $res = model('common/member/MemberLogic', 'logic')->viewSocialAccount($memberId, $been_member_id);
        $res['code'] == SUCCESS ? Db::commit() : Db::rollback();

        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function:查看社交账户次数
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getViewSocialAccountNum()
    {
        //get params
        $memberId = $this->memberId;
        $been_member_id = input('post.show_member_id/d', 0);
        $type = input('post.type/d', 0); //查看0微信  1私聊

        //model
        $memberModel = model('common/member/Member');

        //get data
        $field = 'm.id,m.avatar,m.nickname,a.name as city,m.real_verify,m.video_verify,m.birthday,m.height,m.weight,m.content_types,m.expect_object,m.wechat,m.wechat_hide';
        $been_member = $memberModel->getMemberInfo($been_member_id, $field);

        //judge
        if (empty($been_member)) $this->api_ajaxReturn(ERROR, '查看的会员不存在');
        if ($type == 0) if ($been_member['wechat_hide'] == 1) $this->api_ajaxReturn(ERROR, '会员已隐藏');

        //logic
        $authLogic = model('common/AuthLogic', 'logic');
        $levelModel = model('common/member/Level');
//        $viewLogic = model('common/view/ViewLogLogic', 'logic');

        $data = [];
        $is_expire = $authLogic->isExpire($memberId, $been_member_id, 2); //社交信息

        $surplus_num = $authLogic->getDaySurplusViewNum($memberId, $levelModel::DAY_VIEW_MEMBER_SOCIAL_ACCOUNT_NUM);
        if (isset($surplus_num['code']) && $surplus_num['code'] == ERROR) $this->api_ajaxReturn($surplus_num['code'], $surplus_num['msg'], $surplus_num['result']);
        $data['surplus_num'] = $surplus_num;


        if ($is_expire == true) {//过期
            $data['direct_view'] = $data['surplus_num'] == 0 ? 3 : 2;
        } else {
            $data['direct_view'] = 1;
        }


        $cost = moduleConfig('cost');
        $data['social_account_cost'] = $cost['social_account_cost'];

        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }

    /**
     * User: Simony
     * Function: 拉黑列表
     * @throws \think\exception\DbException
     */
    public function getBlackList()
    {
        $memberId = $this->memberId;
        $page = input('post.per_page/d', 10);
        $type = input('post.type/d', 2);


        $where = ['f.member_id' => $memberId, 'f.type' => 2, 'f.status' => 1];
        $followBlacklistModel = model('common/member/FollowBlacklist');
        $res = $followBlacklistModel->alias('f')
            ->join('member m', 'f.been_member_id=m.id', 'right')
            ->where($where)
            ->field('m.id,m.avatar,m.sex,m.nickname')
            ->order('f.create_time desc');

        $res = $res->paginate($page, false, ['query' => request()->param()]);
        $res = $res->toArray();

        $this->api_ajaxReturn(SUCCESS, '获取成功', $res);
    }


    /**
     * User: Simony
     * Function:钱包
     */
    public function wallet()
    {
        $memberId = $this->memberId;

        $memberModel = model('common/member/Member');

        $field = "id,available_balance,unissued_balance,alipay";
        $member = $memberModel->getInfoByID($memberId, $field);

        $platform = sysConfig('platform');


        $data = [
            'rate' => $platform['withdrawal_rate'] ?? 1,
            'fee_rate' => $platform['withdrawal_fee_rate'] ?? 0,
            'balance' => $member['available_balance'] + $member['unissued_balance'],
            'turn_available_days' => $platform['turn_available_days'] ?? 0,
        ];

        $data = array_merge($data, $member->toArray());
        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }

    /**
     * User: Simony
     * Function:提现
     */
    public function withdrawal()
    {
        $memberId = $this->memberId;

        $scene = input('scene/d', 0);

        if (!in_array($scene, [0, 1])) $this->api_ajaxReturn(ERROR, '场景必须是查看或操作');

        $platform = sysConfig('platform');
        $withdrawal_min_amount = $platform['withdrawal_min_amount'] ?? 0;
        $withdrawal_max_amount = $platform['withdrawal_max_amount'] ?? 0;
        if ($scene == 0) {  //查看
            $memberModel = model('common/member/Member');
            $field = "id,available_balance,alipay,wechat";
            $member = $memberModel->getInfoByID($memberId, $field);


            $rate = $platform['withdrawal_rate'] ?? 1;
            $fee_rate = $platform['withdrawal_fee_rate'] ?? 0;


            $data = [
                'id' => $member['id'],
                'available_balance' => $member['available_balance'],
                'rate' => $rate,
                'fee_rate' => $fee_rate,
                'customer_service_wechat' => $platform['customer_service_wechat'] ?? '',
                'withdrawal_min_amount' => $withdrawal_min_amount,
                'withdrawal_max_amount' => $withdrawal_max_amount,
            ];
            foreach (config('app.pay_type') as $v) {
                if ($v['state'] == 1) {
                    unset($v['state']);
                    $v['account'] = $v['paymethod'] == 2 ? $member['alipay'] : $member['wechat'];

                    $data['pay_list'][] = $v;
                }
            }


            $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
        } elseif ($scene == 1) {

            $money = input('money/d', 0);
            $paymethod = input('paymethod/d', 2);

            if ($money <= 0) $this->api_ajaxReturn(ERROR, '金额必须大于0');
            if ($money < $withdrawal_min_amount || $money > $withdrawal_max_amount) $this->api_ajaxReturn(ERROR, '每次提现范围' . $withdrawal_min_amount . '-' . $withdrawal_max_amount . '之间');


            Db::startTrans();
            $res = model('common/withdraw/WithdrawLogic', 'logic')->withdrawal($memberId, $money, $paymethod);
            if ($res['code'] != SUCCESS) {
                Db::rollback();
                $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
            }
            Db::commit();
            $this->api_ajaxReturn($res['code'], '添加记录成功', $res['result']);
        }
    }


    /**
     * User: Simony
     * Function:绑定支付宝
     */
    public function bindAlipay()
    {
        $memberId = $this->memberId;
        $scene = input('scene/d', 0);
        if (!in_array($scene, [0, 1])) $this->api_ajaxReturn(ERROR, '场景必须是查看或操作');

        $memberModel = model('common/member/Member');
        if ($scene == 0) {
            $field = "alipay,alipay_name";
            $member = $memberModel->getInfoByID($memberId, $field);
            $this->api_ajaxReturn(SUCCESS, '获取成功', $member);
        } elseif ($scene == 1) {
            $alipay_name = input('alipay_name/s', '');
            $alipay = input('alipay/s', '');
            if (empty($alipay) || empty($alipay_name)) $this->api_ajaxReturn(ERROR, '支付宝和支付宝名称必填');

            $update_data = [
                'alipay' => $alipay,
                'alipay_name' => $alipay_name,
            ];
            $res = $memberModel->editByID($memberId, $update_data);
            return $res ? $this->api_ajaxReturn(SUCCESS, '操作成功') : $this->api_ajaxReturn(ERROR, '操作失败');
        }

    }

    /**
     * User: Simony
     * Function:充值记录
     */
    public function getRechargeLog()
    {
        $memberId = $this->memberId;
        $page = input('post.per_page/d', 10);

        $rechargeLogModel = model('common/member/RechargeLog');

        $field = 'id,money,create_time,recharge_type';
        $where = ['member_id' => $memberId, 'state' => 1];
        $rechargeLogModel->getList($where, $page, $field, 'id desc');
        $data = $rechargeLogModel->page_info;

        foreach ($data as &$v) {
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $v['money'] = intval($v['money']);
        }


        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }

    /**
     * User: Simony
     * Function:提现记录
     */
    public function withdrawLog()
    {
        $memberId = $this->memberId;
        $page = input('post.per_page/d', 10);

        $withdrawModel = model('common/withdraw/Withdraw');

        $field = 'id,money,create_time,real_money,state,price';
        $withdrawModel->getList(['member_id' => $memberId], $page, $field, 'id desc');
        $data = $withdrawModel->page_info;

        foreach ($data as &$v) {
            $v['money'] = intval($v['money']);
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }


        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }

    /**
     * User: Simony
     * Function:购买日志
     */
    public function buyLog()
    {
        $memberId = $this->memberId;
        $page = input('post.per_page/d', 10);

        $blanceLogModel = model('common/member/BlanceLog');
        $field = 'id,desc,create_time,money';
        $where = [
            'member_id' => $memberId,
            'pay_type' => 0, //必须余额支付
            'op_type' => 0,//必须购买
        ];

        $blanceLogModel->getList($where, $page, $field, 'id desc');
        $data = $blanceLogModel->page_info;
        foreach ($data as &$v) {
            $v['money'] = abs($v['money']);
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }

    /**
     * User: Simony
     * Function:视频验证
     */
    public function videoVerify()
    {
        //param
        $memberId = $this->memberId;
        $verify_content = input('post.verify_content', '');
        if (empty($verify_content)) $this->api_ajaxReturn(ERROR, '验证内容不能为空');

        $fv = request()->file('video');
        if (empty($fv)) $this->api_ajaxReturn(ERROR, '视频文件不能为空');


        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($memberId);
        if ($member['real_verify'] == 0) $this->api_ajaxReturn(ERROR, '必须先真人认证，才能视频认证');
        if ($member['video_verify'] == 1) $this->api_ajaxReturn(ERROR, '视频认证已通过请勿再次验证');


        $videoVerifyModel = model('common/member/VideoVerify');

        $where = ['member_id' => $memberId, 'status' => 1];
        $video = $videoVerifyModel->getInfo($where);

        if ($video) {
            if ($video['status'] == 1) $this->api_ajaxReturn(ERROR, '有待处理的视频认证，请勿重复提交');
            if ($video['status'] == 2) $this->api_ajaxReturn(ERROR, '认证已通过无需多次认证');
        }


        $fileModel = model('common/member/File');
        $img = model('common/member/File')->getInfo(['member_id' => $memberId, 'table_id' => $memberId, 'type' => 7, 'status' => 1]);
        if (empty($img)) $this->api_ajaxReturn(ERROR, '真人认证图片不存在');

        //复制新认证图片
        $fileLogic = model('common/file/FileLogic', 'logic');
        $old_absoluteUrl = $img['url'];
        $path_info = pathinfo($old_absoluteUrl);
        $new_absoluteUrl = $path_info['dirname'] . DS . md5($img['url']) . "." . $path_info['extension'];
        $fileLogic->fileExists($old_absoluteUrl) ? $fileLogic->copyFile($old_absoluteUrl, $new_absoluteUrl) : $this->api_ajaxReturn(ERROR, '认证图片不存在');

        //上传视频
        $dir = config('app.other_path.video_verify') . DS;
        $file_name = md5($memberId);
        $info = $fv->validate(['ext' => '3gp,rmvb,wmv,avi,mkv,mp3,mp4,mov,MOV,json'])->move($dir, $file_name);
        if (!$info) $this->api_ajaxReturn(ERROR, $fv->getError());

        $video_absoluteUrl = DS . $dir . str_replace('\\', '/', $info->getSaveName());

        Db::startTrans();
        $current_time = time();

        $add_video_verify = $videoVerifyModel->add(
            [
                'member_id' => $memberId,
                'create_time' => $current_time,
                'verify_content' => $verify_content
            ]
        );

        if (!$add_video_verify) {
            Db::rollback();
            $fileLogic->deleteFile($new_absoluteUrl);
            $fileLogic->deleteFile($video_absoluteUrl);
            $this->api_ajaxReturn(ERROR, '申请认证失败');
        }

        $add_file_img = [
            'member_id' => $memberId,
            'table_id' => $add_video_verify,
            'type' => 4,
            'status' => 1,
            'url' => $new_absoluteUrl,
            'create_time' => $current_time
        ];
        $add_file_video = $add_file_img;
        $add_file_video['url'] = $video_absoluteUrl;

        $add_file = $fileModel->addAll([$add_file_img, $add_file_video]);
        if (!$add_file) {
            Db::rollback();
            $fileLogic->deleteFile($new_absoluteUrl);
            $fileLogic->deleteFile($video_absoluteUrl);
            $this->api_ajaxReturn(ERROR, '申请认证失败');
        }

        Db::commit();
        $noticleLogic = model('common/Noticle', 'logic');
        $noticleLogic->sendAutoTxt($memberId, $noticleLogic::VIDEO_VERIFY_NOTICE);

        $this->api_ajaxReturn(SUCCESS, '申请认证成功');

    }


    /**
     * User: Simony
     * mobileapp/member/promotionPage
     * Function: 推广页
     */
    public function promotionPage()
    {
        $memberId = $this->memberId;

        $memberModel = model('common/member/Member');
        $member = $memberModel->getInfoByID($memberId);

        $bonusModel = model('common/bonus/Bonus');

        $where = [
            ['member_id', 'eq', $memberId],
            ['done', 'eq', 1],
        ];
        $total_netincome = $bonusModel->getSum($where, 'netincome'); //已发总佣金
        $total_recommend_money = $bonusModel->getSum($where, 'recommend_money');
        $total_commission_money = $bonusModel->getSum($where, 'commission_money');

        $current_start_time = strtotime(date('Y-m-d'));//今天0点
        $where[] = ['grant_time', 'gt', $current_start_time]; //大于0点时间

        $day_total_recommend_money = $bonusModel->getSum($where, 'recommend_money');
        $day_total_commission_money = $bonusModel->getSum($where, 'commission_money');


        $platform = sysConfig('platform');

        $data = [
            'total_netincome' => $total_netincome,
            'total_recommend_money' => $total_recommend_money,
            'total_commission_money' => $total_commission_money,
            'day_total_recommend_money' => $day_total_recommend_money,
            'day_total_commission_money' => $day_total_commission_money,
            'invite_code' => $member['invite_code'],
            'promotion_description' => $platform['promotion_description'][$member['sex']] ?? '',
        ];

        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }


    /**
     * User: Simony
     * Function:意见反馈
     */
    public function feedback()
    {
        $memberId = $this->memberId;

        $content = input('post.content/s', '');
        if (empty($content)) $this->api_ajaxReturn(ERROR, '意见内容不能为空');

        $res = model('common/feedback/Feedback')->add([
            'member_id' => $memberId,
            'content' => $content,
            'create_time' => time()
        ]);
        $res ? $this->api_ajaxReturn(SUCCESS, '操作成功', ['id' => $res]) : $this->api_ajaxReturn(ERROR, '操作失败');
    }


    /**
     * User: Simony
     * Function: 关注列表
     */
    public function followList()
    {
        //get params
        $memberId = $this->memberId;
        $page_size = input('post.per_page/d', 10);

        //get data
        $res = model('common/member/MemberLogic', 'logic')->getMemberListByFollow($memberId, $page_size);

        //return
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }

    /**
     * User: Simony
     * Function: 次数解锁相册
     */
    public function timesUnlockAlbum()
    {
        $memberId = $this->memberId;
        $been_member_id = input('post.been_member_id');

        Db::startTrans();
        $res = model('common/member/MemberLogic', 'logic')->timesUnlockAlbum($memberId, $been_member_id);
        $res['code'] == SUCCESS ? Db::commit() : Db::rollback();
        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User: Simony
     * Function: 真人认证
     */
    public function realNameAuth()
    {
        $memberId = $this->memberId;
        $file_id = input('post.file_id');
        $token = input('post.token');

        $fileModel=model('common/member/File');

        Db::startTrans();
        $res = model('common/member/MemberLogic', 'logic')->realNameAuth($memberId, $file_id, $token);
        if ($res['code'] != SUCCESS) {
            Db::rollback();
            $file = model('common/member/File')->getInfo(['member_id' => $memberId, 'id' => $file_id, 'type' => 7, 'status' => 1]);
            if ($file) {
                $fileModel->delByID($file_id);
                model('common/file/FileLogic', 'logic')->deleteFile($file['url']);
            }
            $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
        }

        $fileModel->editByID($file_id,['is_oneself'=>1]);
        Db::commit();

        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User: Simony
     * Function:真人认证图片路径
     * @return array
     */
    public function getRealNameAuthImg()
    {
        $memberId = $this->memberId;

        $file = model('common/member/File')->getInfo(['member_id' => $memberId, 'type' => 7, 'status' => 1], 'id,url');

        empty($file) ? $this->api_ajaxReturn(ERROR, '找不到真人认证图片') : $this->api_ajaxReturn(SUCCESS, '获取成功', $file);

    }

    /**
     * 获取App设置
     */
    public function getAppSetting()
    {
        $memberId = $this->memberId;
        $data = model('common/member/AppSettings')->getSetting($memberId);
        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }

    /**
     * 更新app设置
     */
    public function updateAppSetting()
    {
        $memberId = $this->memberId;
        $settings = input('post.settings', []);
        $model = model('common/member/AppSettings');
        if (!is_array($settings) || empty($settings)) {
            $this->api_ajaxReturn(ERROR, '设置不能为空', []);
        }
        $res = $model->updateSetting($memberId, $settings);
        if ($res) {
            $this->api_ajaxReturn(SUCCESS, '设置已更新', []);
        }
        $this->api_ajaxReturn(ERROR, '设置更新失败', []);
    }


    /**
     * User: Simony
     * Function:收益记录
     */
    public function profitLog()
    {
        $memberId = $this->memberId;
        $page = input('post.per_page/d', 10);

        $blanceLogModel = model('common/member/BlanceLog');

        $field = 'id,desc,create_time,money';
        $where = ['member_id' => $memberId, 'op_type' => 4];
        $blanceLogModel->getList($where, $page, $field, 'create_time desc');
        $data = $blanceLogModel->page_info;

        foreach ($data as &$v) {
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $v['money'] = intval($v['money']);
            $desc = explode(',', $v['desc']);
            array_pop($desc);
            $v['desc'] = implode(',', $desc);
        }


        $this->api_ajaxReturn(SUCCESS, '获取成功', $data);
    }


    /**
     * User: Simony
     * Function:发送红包
     */
    public function sendRedpacket()
    {
        $memberId = $this->memberId;
        $receive_flag_id = input('post.receive_flag_id/d', 0); //标识id 接收会员id或者，接收的组
        $receive_type = input('post.receive_type/d', 1); //1会员 2组
        $money = input('post.money/d', 0); //金额
        $number = input('post.number/d', 1);//红包个数
        $des = input('post.des/d', '恭喜发财');

        if (!in_array($receive_type, [1, 2])) $this->api_ajaxReturn(ERROR, '发送类型只能是指定会员，或者组群');
        if ($money <= 0) $this->api_ajaxReturn(ERROR, '金币数必须大于0');
        if ($number <= 0) $this->api_ajaxReturn(ERROR, '红包个数必须大于0');
        if ($money < $number) $this->api_ajaxReturn(ERROR, '金额数必须大于红包个数');

        $memberModel = model('common/member/Member');
        switch ($receive_type) {
            case 1:
                $number = 1;
                $receive_member = $memberModel->getInfo($receive_flag_id);
                if (empty($receive_member)) $this->api_ajaxReturn(ERROR, '发送给了不存在得会员');
                break;
            case 2:
                $this->api_ajaxReturn(ERROR, '暂不支持群发');
                break;
            default :
                $this->api_ajaxReturn(ERROR, '发送类型错误');
                break;
        }

        $current_time = time();
        $add_data = [
            'member_id' => $memberId,
            'receive_flag_id' => $receive_flag_id,
            'money' => $money,
            'surplus_money' => $money,
            'number' => $number,
            'des' => $des,
            'create_time' => $current_time,
            'expire_time' => $current_time + 86400 * 24, //一天后过期
        ];

        Db::startTrans();
        $redpacket_id = model('common/redpacket/Redpacket')->add($add_data);
        if (!$redpacket_id) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '发送失败');
        }

        //更新用户余额
        $desc = '聊天红包';
        $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($memberId, -$money, 0, 3, $desc, $redpacket_id);
        if ($update_available_balance_res['code'] != SUCCESS) {
            Db::rollback();
            $this->api_ajaxReturn($update_available_balance_res['code'], $update_available_balance_res['msg']);
        }

        Db::commit();
        $this->api_ajaxReturn(SUCCESS, '发送成功', ['id' => $redpacket_id]);
    }


    /**
     * User: Simony
     * Function: 红包领取时间
     */
    public function receiveRedpacket()
    {
        $memberId = $this->memberId;
        $redpacket_id = input('post.redpacket_id/d', 0);

        $redpacketModel = model('common/redpacket/Redpacket');
        $redpacket = $redpacketModel->getInfoByID($redpacket_id);

        if (empty($redpacket)) $this->api_ajaxReturn(ERROR, '红包不存在');

        $current_time = time();
        switch ($redpacket['receive_type']) {
            case 1:
                if ($redpacket['receive_flag_id'] != $memberId) $this->api_ajaxReturn(ERROR, '红包是发送给别人的，您不能领取');
                if ($redpacket['surplus_money'] <= 0) $this->api_ajaxReturn(ERROR, '红包已领完');
                if ($redpacket['expire_time'] < $current_time) $this->api_ajaxReturn(ERROR, '红包已过期');

                //领取红包
                $add_data = [
                    'redpacket_id' => $redpacket['id'],
                    'member_id' => $memberId,
                    'send_member_id' => $redpacket['member_id'],
                    'money' => $redpacket['money'],
                    'create_time' => $current_time,
                ];
                $redpacketReceiveLogModel = model('common/redpacket/RedpacketReceiveLog');

                Db::startTrans();
                $redpacket_receive_log_id = $redpacketReceiveLogModel->add($add_data);
                if (!$redpacket_receive_log_id) {
                    Db::rollback();
                    $this->api_ajaxReturn(ERROR, '领取失败');
                }

                $desc = '聊天红包';
                $update_available_balance_res = model('common/member/MemberLogic', 'logic')->updateAvailableBalance($memberId, $redpacket['money'], 0, 4, $desc, $redpacket['id']);
                if ($update_available_balance_res['code'] != SUCCESS) {
                    Db::rollback();
                    $this->api_ajaxReturn($update_available_balance_res['code'], $update_available_balance_res['msg']);
//                    $this->api_ajaxReturn(ERROR,'领取失败');
                }
                Db::commit();

                $this->api_ajaxReturn(SUCCESS, '领取成功', ['moeny' => $redpacket['money'], 'des' => $redpacket['des']]);
                break;
            case 2:
                $this->api_ajaxReturn(ERROR, '暂不支持领取群红包呢');
                break;
            default :
                $this->api_ajaxReturn(ERROR, '红包类型暂不支持领取');
                break;
        }
    }


    /**
     * User:Simony
     * Function: 申请邀请码添加修改
     */
    public function applyInviteCode()
    {
        //params
        $memberId = $this->memberId;

        //model
        $memberApplyModel = model('common/member/MemberApply');
        $member_apply = $memberApplyModel->getInfo(['state' => [0, 1, 3], 'member_id' => $memberId]); //0审核中 1通过 3是激活
        if ($member_apply) $this->api_ajaxReturn(ERROR, '申请处理中或已通过请勿重复申请');

        $member = model('common/member/Member')->getInfoByID($memberId);

        $fileLogic = model('common/file/FileLogic', 'logic');
        $old_absoluteUrl = $member['avatar'];
        $path_info = pathinfo($member['avatar']);
        $new_absoluteUrl = $path_info['dirname'] . DS . 'apply_avatar_' . $path_info['basename'];
        $fileLogic->fileExists($old_absoluteUrl) ? $fileLogic->copyFile($old_absoluteUrl, $new_absoluteUrl) : $this->api_ajaxReturn(ERROR, '用户头像不存在');

        $res = $memberApplyModel->add([
            'member_id' => $memberId,
            'avatar' => $new_absoluteUrl,
            'nickname' => $member['nickname'],
            'birthday' => $member['birthday'],
            'sex' => $member['sex'],
            'province' => $member['province'],
            'city' => $member['city'],
            'district' => $member['district'],
            'username' => $member['username'],
            'wechat' => $member['wechat'],
            'profession' => $member['profession'],
            'content_types' => $member['content_types'],
            'expect_object' => $member['expect_object'],
            'height' => $member['height'],
            'weight' => $member['weight'],
            'apply_time' => time(),
            'state' => 0,
        ]);


//        $member = model('common/member/Member')->getInfoByID($memberId);
        $platform = sysConfig('platform');
        $customer_service_member_id = $platform['customer_service_member_id'] ?? 0;
        (new \easemob\EasemobIm())->sendText($memberId, 'users', $customer_service_member_id, '我申请激活，请您帮忙处理一下，谢谢！', ['msg_type' => 8, 'type' => 0]);

        $this->api_ajaxReturn(SUCCESS, '申请成功', ['id' => $res]);
    }


    /**
     * User: Simony
     * Function:设置临时邀请码
     */
    public function memberInviteTemp()
    {
        $parent_invite_code = input('post.parent_invite_code/s', '');
        $username = input('post.username/s', '');

        if (!preg_match('/^1[3-9]\d{9}$/', $username)) $this->api_ajaxReturn(ERROR, '手机号码不正确');
        if (empty($parent_invite_code)) $this->api_ajaxReturn(ERROR, '验证码不能为空');


        $memberInviteTempModel = model("common/member/MemberInviteTemp");
        $memberModel = model("common/member/Member");

        $where = ['username' => $username];

        $member = $memberModel->getInfo($where);

        if (empty($member)) {
            $data = [
                'parent_invite_code' => $parent_invite_code, //记住即使是错的邀请码也让他成功添加
                'username' => $username
            ];
            $member_invite_temp = $memberInviteTempModel->getInfo($where);

            $member_invite_temp ? $memberInviteTempModel->edit($where, $data) : $memberInviteTempModel->add($data);
        }

        $this->api_ajaxReturn(SUCCESS, '提交成功');
    }


    /**
     * User: Simony
     * Function:合伙人业绩
     */
    public function partnerPerformance()
    {
        $memberId = $this->memberId;
        $year = input('year/s', '');
        if (empty($year)) $this->api_ajaxReturn(ERROR, '年份必填');

        $res = model('common/member/MemberLogic', 'logic')->partnerPerformance($memberId, $year);

        $this->api_ajaxReturn($res['code'], $res['msg'], $res['result']);

    }
}
